import React, { Component } from "react";
import Header from "./Header";

class App extends Component{
    state = {
        val:"",
        list:[]
    }
    add = () => {
        let {list,val} = this.state;
        this.setState({
            //改变引用类型变量的状态，一定要改变它指向的地址
            list:[...list,{
                title:val,
                done:false,
                id:Date.now()
            }]
        },() => {//state状态更新完后调用，可以拿到最新的状态值
            console.log(this.state.list);
        });
    }
    changeVal = (e) => {
        this.setState({
            val: e.target.value
        })
    }
    deleteItem = (id) => {
        this.setState({list:this.state.list.filter(item => id !== item.id)});
    }
    toggleItem = (id) => {
        const newList = this.state.list.map(item => {
            return item.id === id?{...item,done:!item.done}:item;
        });

        this.setState({
            list:newList
        });
    }
    render() {
        return <div>
            <Header />
            <input value={this.state.val} onChange={this.changeVal} type="text"/>
            <button onClick={this.add}>添加</button>
            <ul>
                {
                    this.state.list.map(item => {
                        return <li style={{
                            background:item.done?"red":"#fff"
                        }} key={item.id}>
                            <span onClick={() => this.toggleItem(item.id)}>{
                                item.done
                                ?<span>√</span>
                                :<input type="checkbox" />
                            }</span>
                            <span style={{
                                textDecoration:item.done?"line-through":"none"
                            }}>{item.title}</span>
                            <button onClick={() => this.deleteItem(item.id)}>X</button>
                        </li>
                    })
                }
            </ul>
        </div>
    }
}

export default App;